package sy.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sy.model.Tinviterecord;
import sy.model.Tuser;
import sy.pageModel.Rinviterecord;
import sy.pageModel.SessionInfo;
import sy.pageModel.User;
import sy.service.InviteServiceI;
import sy.service.UserServiceI;
import sy.util.ConfigUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 邀请
 * 
 * @author 甘涛
 * 
 */
@Controller
@RequestMapping("/inviteController")
public class InviteController extends BaseController {
	@Autowired
	private InviteServiceI inviteService;
	
	@Autowired
	private UserServiceI userService;
	/**
	 * 添加邀请记录信息
	 * 
	 * @param
	 * 
	 */

	@ResponseBody
	@RequestMapping("/addinviterecord")
	public String addtaskrecord(Rinviterecord  invite,HttpSession session,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
		SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());

		if(sessionInfo == null){
			jsobj.put("status", -1);
			jsobj.put("msg", "登录超时");
		}else{
		try {
            User u = userService.get(sessionInfo.getId());

            //查询是否重复邀请
            Map<String,Object> params=new HashMap<String,Object>();

            params.put("imei",invite.getImei());

            List<Tinviterecord> tinviterecords=inviteService.getTinviterecord(params);

            if(tinviterecords!=null&&tinviterecords.size()>0){//存在重复邀请记录
                jsobj.put("status", "0");
                jsobj.put("msg", "不能重复邀请");
            }else{

                //不能自己邀请自己
                if(invite.getInviteuserid().equals(invite.getUserid())){
                    jsobj.put("status", "0");
                    jsobj.put("msg", "不能邀请自己");
                }else if(inviteService.inviteme(invite.getUserid(), invite.getInviteuserid())){//不能相互邀请
                	  jsobj.put("status", "0");
                      jsobj.put("msg", "不能相互邀请");
                }
                else{
                    invite.setUserid(invite.getInviteuserid());
                    invite.setInviteuserid(sessionInfo.getUserid()+"");	//设置邀请人的ID
                    invite.setScore(30000);
                    invite.setRealscore(u.getTotalscore());
                    invite.setImei(invite.getImei());
                    inviteService.add(invite);
                    jsobj.put("status", "1");
                    jsobj.put("msg", "邀请成功");

                    //增加一次刮奖机会
                    userService.updateGglCount(invite.getInviteuserid(),1);
                    //更新推广用户总积分
                    Tuser user=userService.getUserByUserId(invite.getUserid());
                    if(user!=null){
                        //推广用户id
                        User tguser=new User();
                        BeanUtils.copyProperties(user,tguser);
                        if(tguser!=null){
                            if(tguser.getTotalscore()==null){
                                tguser.setTotalscore(30000);
                            }else{
                                tguser.setTotalscore(tguser.getTotalscore()+30000);
                            }
                            if(tguser.getUnchangedscore()==null){
                                tguser.setUnchangedscore(30000);
                            }else{
                                tguser.setUnchangedscore(tguser.getUnchangedscore()+30000);
                            }
                            userService.editotlescore(tguser);
                        }


                    }

                }


            }

		} catch (Exception e) {

			e.printStackTrace();
			jsobj.put("status", "0");
			jsobj.put("msg", "邀请失败");
		}
		}
		return jsobj.toJSONString();
	}


    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request){
        String id=request.getParameter("id");
        JSONObject jsobj = new JSONObject();
        try {
            inviteService.delete(id);
            jsobj.put("msg",true);
        }catch (Exception e){
            jsobj.put("msg",false);
            e.printStackTrace();
        }

        return jsobj.toJSONString();

    }
	/**
	 * 查询邀请记录信息
	 * 
	 * @param
	 * @param
	 * @return
	 */
	@RequestMapping("/inviterecord")
	@ResponseBody
	public String getnewexchange(HttpSession session,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
		SimpleDateFormat formatterstr = new SimpleDateFormat("MM-dd HH:mm");
		SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
		if(sessionInfo == null){
			jsobj.put("status", -1);
			jsobj.put("msg", "登录超时");

		}else{
		try {
			List<Tinviterecord>  task = inviteService.gettask(sessionInfo.getUserid()+"");
			List<Tinviterecord>  tasknew  =  new ArrayList<Tinviterecord>();
			for(Tinviterecord taskcp : task){
				Tinviterecord ivt =	 new Tinviterecord();
				ivt.setImei(taskcp.getImei());
				ivt.setInviteuserid(taskcp.getInviteuserid());
                Tuser u = userService.getUserByUserId(taskcp.getInviteuserid());

				ivt.setNickname(u.getName());
				ivt.setRealscore(taskcp.getRealscore());
				ivt.setRegistertime(formatterstr.format(u.getCreatedatetime()));
				ivt.setScore(taskcp.getScore());
				ivt.setUserid(taskcp.getUserid());
				tasknew.add(ivt);
			}
			jsobj.put("status", "1");
			jsobj.put("msg", tasknew);
		} catch (Exception e) {
			e.printStackTrace();
			jsobj.put("status", "0");
			jsobj.put("msg", "系统错误");
		}
		}
		return jsobj.toJSONString();
	}

	public String getCount(String userid){
		try {
			return inviteService.getCount(userid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
}
